<!--
  * 计划站位表信息
  *
  * @Author:    lmabbe
  * @Date:      2025-06-27 19:10:13
  * @Copyright  lmabbe
-->
<template>
  <a-modal
    :destroyOnClose="true"
    :maskClosable="false"
    :open="visibleFlag"
    :title="form.planPositionId ? '编辑' : '添加'"
    :width="850"
    @cancel="onClose"
  >
    <a-form ref="formRef" :label-col="{ style: 'width: 100px; display: inline-block; vertical-align: inherit;' }" :model="form" :rules="rules">
      <a-row>
        <a-col :span="12">
          <a-form-item label="机器信息" name="machineId">
            <a-select
              v-model:value="form.machineId"
              :allowClear="true"
              :style="`width: 100%`"
              placeholder="请选择选择机器"
              @change="
                (value) => {
                  let data = machineInfoData.find((item) => item.machineId === value);
                  form.machineName = data.machineName;
                  loadMachinePositionData();
                  form.positionId = undefined;
                }
              "
            >
              <a-select-option v-for="item in machineInfoData" :key="item.machineId" :value="item.machineId">
                {{ item.machineName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="机器站位" name="positionId">
            <a-select
              v-model:value="form.positionId"
              :allowClear="true"
              :style="`width: 100%`"
              placeholder="请选择选择机器站位"
              @change="
                (value) => {
                  let data = machinePositionData.find((item) => item.positionId === value);
                  form.systemRealPosition = data.realPosition;
                }
              "
            >
              <a-select-option v-for="item in machinePositionData" :key="item.positionId" :value="item.positionId">
                {{ item.positionName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="物料类型" name="materialType">
            <SmartEnumSelect
              v-model:value="form.materialType"
              enum-name="WORK_ORDER_PRODUCTION_PLAN_POSITION_MATERIAL_TYPE_ENUM"
              placeholder="物料类型"
              width="100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="物料编码" name="materialCode">
            <TableSelect
              v-model:modelValue="form.materialCode"
              :columns="[
                { title: '物料编号', dataIndex: 'materialCode', key: 'materialCode' },
                { title: '物料名称', dataIndex: 'materialName', key: 'materialName' },
                { title: '物料规格', dataIndex: 'materialSpec', key: 'materialSpec' },
                { title: '归属客户', dataIndex: 'belongCustomerAbbreviation', key: 'belongCustomerAbbreviation' },
              ]"
              :options="materialData"
              :placeholder="'输入物料编号/名称/规格'"
              @search="handleMaterialSearch"
              @select="handleMaterialSelect"
            />
          </a-form-item>
        </a-col>
        <a-col v-if="form.materialType === 2" :span="12">
          <a-form-item label="主料编码" name="mainMaterialCode">
            <TableSelect
              v-model:modelValue="form.mainMaterialCode"
              :columns="[
                { title: '物料编号', dataIndex: 'materialCode', key: 'materialCode' },
                { title: '物料名称', dataIndex: 'materialName', key: 'materialName' },
                { title: '物料规格', dataIndex: 'materialSpec', key: 'materialSpec' },
                { title: '归属客户', dataIndex: 'belongCustomerAbbreviation', key: 'belongCustomerAbbreviation' },
              ]"
              :options="materialData"
              :placeholder="'输入物料编号/名称/规格'"
              @search="handleMaterialSearch"
              @select="handleMainMaterialSelect"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="用量" name="dosage">
            <a-input-number :min="1" v-model:value="form.dosage" placeholder="用量" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="位置" name="location">
            <a-textarea v-model:value="form.location" placeholder="位置" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-textarea v-model:value="form.remark" placeholder="备注" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { nextTick, reactive, ref } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import TableSelect from '/@/components/TableSelect/index.vue';
  import { productionPlanPositionApi } from '/@/api/business/product/order/production-plan-position-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
  import { machineInfoApi } from '/@/api/business/product/machine/machine-info-api.js';
  import { materialInfoApi } from '/@/api/business/basic/material/material-info-api.js';
  import { machinePositionInfoApi } from '/@/api/business/product/machine/machine-position-info-api.js';

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);

  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    loadMachineInfoData();
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
    planPositionId: undefined, //计划站位ID
    planId: undefined, //计划ID
    lineId: undefined, // 线别ID
    stationTablePosition: undefined, //站位表站位
    positionId: undefined, //机器站位ID
    systemRealPosition: undefined, //系统中站位
    machineId: undefined, //机器ID
    machineName: undefined, //机器名称
    materialType: undefined, //物料类型:[1:主料，2:替代料]
    materialCode: undefined, //物料编码
    materialName: undefined, //物料名称
    materialSpec: undefined, //物料规格
    materialDesc: undefined, //物料描述
    mainMaterialCode: undefined, //主料物料编码
    materialUnit: undefined, //物料单位
    dosage: 1, //用量
    location: undefined, //位置
    remark: undefined, //备注
  };

  let form = reactive({ ...formDefault });

  const rules = {
    planId: [{ required: true, message: '计划ID 必填' }],
    positionId: [{ required: true, message: '机器站位 必填' }],
    machineId: [{ required: true, message: '机器信息 必填' }],
    materialType: [{ required: true, message: '物料类型 必填' }],
    materialCode: [{ required: true, message: '物料编码 必填' }],
    mainMaterialCode: [{ required: true, message: '主料物料编码 必填' }],
    dosage: [{ required: true, message: '用量 必填' }],
    location: [{ required: true, message: '位置 必填' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      form.stationTablePosition = form.systemRealPosition;
      if (form.materialType === 1) {
        form.mainMaterialCode = form.materialCode;
      }
      if (form.planPositionId) {
        await productionPlanPositionApi.update(form);
      } else {
        await productionPlanPositionApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  const machineInfoData = ref();

  function loadMachineInfoData() {
    let param = {
      belongLineId: form.lineId,
    };
    machineInfoApi.all(param).then((res) => {
      machineInfoData.value = res.data;
    });
  }

  const machinePositionData = ref();

  function loadMachinePositionData() {
    let params = {
      machineId: form.machineId,
    };
    machinePositionInfoApi.all(params).then((res) => {
      machinePositionData.value = res.data;
    });
  }

  const materialData = ref();

  const handleMaterialSelect = (value) => {
    form.materialCode = value.record.materialCode;
    form.materialName = value.record.materialName;
    form.materialDesc = value.record.materialDesc;
    form.materialSpec = value.record.materialSpec;
    form.materialUnit = value.record.materialUnit;
  };

  const handleMainMaterialSelect = (value) => {
    form.mainMaterialCode = value.record.materialCode;
  };

  const handleMaterialSearch = (searchValue) => {
    let param = {
      keywords: searchValue,
      belongCustomer: form.customerCode,
      materialProperty: 'ROW',
    };
    materialInfoApi.searchTop10(param).then((res) => {
      materialData.value = res.data;
    });
  };
  defineExpose({
    show,
  });
</script>
